<?php
class Helper_Pagination
{
	public $record_amount;		//总纪录数
	public $page_amount;		//总页数
	public $page_index;			//当前页
	public $page_size=10;		//每页纪录数
	
	public $max_page="";		//显示页数上限
	public $align = "right";	//分页字符串对齐方式

	function __construct()
	{
		
	}
	
	private function current_page()
	{
		//处理当前的页码
		$page_index = $_REQUEST['page'];
		
		if( is_array($page_index)) {
			$this->page_index = $page_index[0];
		} else {
			$this->page_index = $page_index;
		}
		
		if( $this->page_index < 1) {
			$this->page_index = 1;
		}
	}
	/**
	 * 生成分页字符串
	 *
	 * @param $record_amount     总纪录数
	 * @param $page_size   每页纪录数
	 * 
	 * @return string        分页字符串
	 */
	function paginate($record_amount, $page_size=PAGE_SIZE)
	{
		$url = $_SERVER['PHP_SELF'].'?';
		$this->record_amount = $record_amount;
		$this->page_size = $page_size;
		// die($this->record_amount .']');
		
		$this->current_page();
		
		//计算总页数		
		$this->page_amount = ceil($this->record_amount/$this->page_size);
		
		if($this->page_amount <= 0 )
		{
			return '';
		} else if( $this->page_index > $this->page_amount ) {
			$this->page_index = $this->page_amount;
		}
		//如果存在分页上限限制，则使显示页数不超过限制。
		$this->max_page && $this->page_amount > $this->max_page && $this->page_amount=$this->max_page;	
	
		//对页面所带参数进行处理：去掉page参数。注意：page参数必须为页面的最后一个参数。
		$pages = $_GET;
		
		if( key_exists('page', $pages) ){
			unset($pages['page']);
		}
		
		$url_query = '';
		foreach($pages as $key=>$value) {
			$url_query .= '&'.$key.'='.$value;
		}
		if( !empty($url_query)) {
			$url .= trim($url_query, '&').'&';
		}
		
		//开始组合分页字符串
		$pages="<div class=\"pages\" id=\"divPagination\" style=\"text-align:{$this->align};\"><a href=\"{$url}page=1\" style=\"font-weight:bold;\">&laquo;</a>";
		
		//小于当前页的分页：最多显示3页
		for($i=$this->page_index-3;$i<=$this->page_index-1;$i++)
		{
			if($i<1) continue;
			$pages.="<a href=\"{$url}page=$i\">$i</a>";
		}		
		//当前页
		$pages.="<b> $this->page_index </b>";		
		//大于当前页的分页：最多显示3页		
		$flag=0;
		if($this->page_index<$this->page_amount){
			for($i=$this->page_index+1;$i<=$this->page_amount;$i++){
				$pages.="<a href=\"{$url}page=$i\">$i</a>";
				$flag++;
				if($flag==4) break;
			}
		}
		
		$pages.="<input type=\"text\" size=\"3\" onkeydown=\"javascript: if(event.keyCode==13){ location='{$url}page='+this.value;return false;}\"><a href=\"{$url}page=$this->page_amount\" style=\"font-weight:bold\">&raquo;</a> 总共: $this->record_amount ( $this->page_index/$this->page_amount 页 )</div>";
		return $pages;
	}
	
	/**
	 * 获得开始的纪录号
	 *
	 */
	function GetStartRecord()
	{
		return ( $this->page_index - 1 ) * $this->page_size;
	}
	
	/**
	 * 获得mysql数据库的limit限制语句
	 *
	 */
	function GetSqlLimit(){
		$start_record = $this->GetStartRecord();
        $limit_str = " limit ".$start_record.",".$this->page_size." ";
        return $limit_str;
	}
}
?>